package ru.javadevelop.homefinans.common;

import android.content.Context;
import android.os.Environment;

import java.io.*;

/**
 * http://t-menu.ru
 * User: navff
 * Date: 23.07.12
 * Time: 10:26
 */
public  class FileUtils {
    public static String readRawTextFile(String path)
    {
        InputStream inputStream = FileUtils.class.getResourceAsStream(path);

        ByteArrayOutputStream ostream = new ByteArrayOutputStream();

        byte[] buf = new byte[10240];
        int bytes;
        try {

            while (-1 != (bytes = inputStream.read(buf)))
                ostream.write(buf, 0, bytes);

        } catch (IOException e) {
            return null;
        }
        finally {
            try { inputStream.close(); } catch (IOException e) {}
        }
        return ostream.toString();
    }

    /**
     * Копирует файл из ресурса на SdCard
     * @param context
     * @param resourceId     Ресурс. Например, R.raw.test
     * @param filePath - путь к файлу, НЕ включая '/sdcard'
     * @param fileName - имя создаваемого файла
     */
    public static void copyFromRawToSdCard(Context context,
                                           int resourceId,
                                           String filePath,
                                           String fileName)
    {

        InputStream rawFile = context.getResources().openRawResource(resourceId);
        File sdCard = Environment.getExternalStorageDirectory();
        File file = new File(sdCard+"/"+filePath, fileName);
        if (!file.exists())
        {
            try
            {
                FileOutputStream fileout = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int bufferLength = 0;
                while ((bufferLength = rawFile.read(buffer))>0)
                {
                    fileout.write(buffer, 0 , bufferLength);
                }
                fileout.close();
            } catch (IOException ex)
            {
                ex.printStackTrace();
                System.exit(-1);
            }
        }


    }
}
